package com.sample;

import java.util.Iterator;

import com.trg.search.ISearch;
import com.trg.search.Search;
import com.trg.search.SearchUtil;
import com.trg.search.Sort;

public class Utils {
	/**
	 * Replaces sorts on the given property (<code>toReplace</code>) with
	 * sorts on the second property (<code>replaceWith</code>). The single
	 * sort to replace can be replaced with multiple sorts. For example, if we
	 * have a generated "fullName" property (<code>parent.name + " > " + name</code>)
	 * we can replace that with two sorts, first by <code>"parent.name"</code>
	 * then by <code>"name"</code>. This would be called as follows
	 * <code>replaceSortProperty(search, "fullName", "parent.name", "name");</code>
	 * 
	 * @return The same search if no changes need to be made or if changes are
	 *         made, a new search with those changes.
	 */
	public static ISearch replaceSortProperty(ISearch search, String toReplace,
			String... replaceWith) {
		Iterator<Sort> itr = search.getSorts().iterator();
		while (itr.hasNext()) {
			if (toReplace.equals(itr.next().getProperty())) {
				// problem found
				Search newSearch = SearchUtil.copy(search, new Search());
				newSearch.clearSorts();
				itr = search.getSorts().iterator();
				while (itr.hasNext()) {
					Sort sort = itr.next();
					newSearch.addSort(sort);
					if (toReplace.equals(sort.getProperty())) {
						sort.setProperty(replaceWith[0]);
						for (int i = 1; i < replaceWith.length; i++) {
							newSearch.addSort(replaceWith[i], sort.isDesc());
						}
					}
				}
				return newSearch;
			}
		}
		return search;
	}
}
